const Koa = require('koa');
const Router = require('koa-router');
const serve = require('koa-static');
const bodyParser = require('koa-bodyparser');
const cors = require('koa-cors');
const path = require('path');
const fs = require('fs-extra');

// 导入模块
const HtmlGenerator = require('./public/js/modules/HtmlGenerator');
const FileManager = require('./public/js/modules/FileManager');

const app = new Koa();
const router = new Router();

// 中间件
app.use(cors());
app.use(bodyParser());
app.use(serve(path.join(__dirname, 'public')));

// 登录页面路由
app.use(async (ctx, next) => {
    if (ctx.path === '/login.html' || ctx.path === '/login') {
        ctx.type = 'html';
        ctx.body = require('fs').readFileSync(path.join(__dirname, 'public/login.html'), 'utf8');
    } else {
        await next();
    }
});

// 用户登录API
router.post('/api/login', async (ctx) => {
    try {
        const { username, password } = ctx.request.body;
        
        // 读取用户数据
        const usersData = await fs.readJson(path.join(__dirname, 'data/users/users.json'));
        const user = usersData.users.find(u => u.username === username && u.password === password);
        
        if (user) {
            // 更新最后登录时间
            user.lastLogin = new Date().toISOString();
            await fs.writeJson(path.join(__dirname, 'data/users/users.json'), usersData, { spaces: 2 });
            
            // 返回用户信息（不包含密码）
            const { password: _, ...userInfo } = user;
            ctx.body = { success: true, user: userInfo };
        } else {
            ctx.status = 401;
            ctx.body = { success: false, message: '用户名或密码错误' };
        }
    } catch (error) {
        console.error('登录错误:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: '服务器错误' };
    }
});

// 获取用户列表API
router.get('/api/users', async (ctx) => {
    try {
        const usersData = await fs.readJson(path.join(__dirname, 'data/users/users.json'));
        ctx.body = usersData;
    } catch (error) {
        console.error('获取用户列表错误:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: '服务器错误' };
    }
});

// 添加用户API
router.post('/api/users', async (ctx) => {
    try {
        const { username, password, role = 'user', displayName } = ctx.request.body;
        
        // 验证必填字段
        if (!username || !password) {
            ctx.status = 400;
            ctx.body = { success: false, message: '用户名和密码不能为空' };
            return;
        }
        
        // 读取用户数据
        const usersData = await fs.readJson(path.join(__dirname, 'data/users/users.json'));
        
        // 检查用户名是否已存在
        if (usersData.users.find(u => u.username === username)) {
            ctx.status = 400;
            ctx.body = { success: false, message: '用户名已存在' };
            return;
        }
        
        // 创建新用户
        const newUser = {
            id: Math.max(...usersData.users.map(u => u.id), 0) + 1,
            username,
            password,
            role,
            displayName: displayName || username,
            createdAt: new Date().toISOString(),
            lastLogin: null
        };
        
        usersData.users.push(newUser);
        await fs.writeJson(path.join(__dirname, 'data/users/users.json'), usersData, { spaces: 2 });
        
        // 返回用户信息（不包含密码）
        const { password: _, ...userInfo } = newUser;
        ctx.body = { success: true, user: userInfo };
    } catch (error) {
        console.error('添加用户错误:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: '服务器错误' };
    }
});

// 删除用户API
router.delete('/api/users/:id', async (ctx) => {
    try {
        const userId = parseInt(ctx.params.id);
        
        // 读取用户数据
        const usersData = await fs.readJson(path.join(__dirname, 'data/users/users.json'));
        
        // 检查用户是否存在
        const userIndex = usersData.users.findIndex(u => u.id === userId);
        if (userIndex === -1) {
            ctx.status = 404;
            ctx.body = { success: false, message: '用户不存在' };
            return;
        }
        
        // 不能删除admin用户
        if (usersData.users[userIndex].username === 'admin') {
            ctx.status = 400;
            ctx.body = { success: false, message: '不能删除超级管理员账户' };
            return;
        }
        
        // 删除用户
        usersData.users.splice(userIndex, 1);
        await fs.writeJson(path.join(__dirname, 'data/users/users.json'), usersData, { spaces: 2 });
        
        ctx.body = { success: true };
    } catch (error) {
        console.error('删除用户错误:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: '服务器错误' };
    }
});

// 更新用户API
router.put('/api/users/:id', async (ctx) => {
    try {
        const userId = parseInt(ctx.params.id);
        const { username, password, role, displayName } = ctx.request.body;
        
        // 读取用户数据
        const usersData = await fs.readJson(path.join(__dirname, 'data/users/users.json'));
        
        // 检查用户是否存在
        const userIndex = usersData.users.findIndex(u => u.id === userId);
        if (userIndex === -1) {
            ctx.status = 404;
            ctx.body = { success: false, message: '用户不存在' };
            return;
        }
        
        // 更新用户信息
        if (username) usersData.users[userIndex].username = username;
        if (password) usersData.users[userIndex].password = password;
        if (role) usersData.users[userIndex].role = role;
        if (displayName) usersData.users[userIndex].displayName = displayName;
        
        await fs.writeJson(path.join(__dirname, 'data/users/users.json'), usersData, { spaces: 2 });
        
        // 返回用户信息（不包含密码）
        const { password: _, ...userInfo } = usersData.users[userIndex];
        ctx.body = { success: true, user: userInfo };
    } catch (error) {
        console.error('更新用户错误:', error);
        ctx.status = 500;
        ctx.body = { success: false, message: '服务器错误' };
    }
});

// 添加预览文件路由
app.use(async (ctx, next) => {
  if (ctx.path.startsWith('/previews/')) {
    const filePath = path.join(__dirname, ctx.path);
    const fs = require('fs-extra');
    
    try {
      if (await fs.pathExists(filePath)) {
        const content = await fs.readFile(filePath, 'utf8');
        ctx.type = 'html';
        ctx.body = content;
      } else {
        ctx.status = 404;
        ctx.body = 'File not found';
      }
    } catch (error) {
      ctx.status = 500;
      ctx.body = 'Server error';
    }
  } else {
    await next();
  }
});

// 初始化管理器
const htmlGenerator = new HtmlGenerator();
const fileManager = new FileManager();

// 保存页面配置
router.post('/api/save', async (ctx) => {
  try {
    const { pageData, filename } = ctx.request.body;
    const result = await fileManager.savePageData(pageData, filename);
    
    if (result.success) {
      ctx.body = result;
    } else {
      ctx.status = 500;
      ctx.body = result;
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { success: false, message: '保存失败', error: error.message };
  }
});

// 读取页面配置
router.get('/api/load/:filename', async (ctx) => {
  try {
    const { filename } = ctx.params;
    const result = await fileManager.loadPageData(filename);
    
    if (result.success) {
      ctx.body = result;
    } else {
      ctx.status = 404;
      ctx.body = result;
    }
  } catch (error) {
    ctx.status = 404;
    ctx.body = { success: false, message: '文件不存在' };
  }
});

// 获取所有保存的页面列表
router.get('/api/pages', async (ctx) => {
  try {
    const result = await fileManager.getPageList();
    ctx.body = result;
  } catch (error) {
    ctx.body = { success: true, data: [] };
  }
});

// 生成预览页面
router.post('/api/preview', async (ctx) => {
  try {
    console.log('预览API被调用');
    const { pageData, filename } = ctx.request.body;
    console.log('接收到的参数:', { filename, pageDataKeys: Object.keys(pageData || {}) });
    
    // 验证页面数据
    const validation = htmlGenerator.validatePageData(pageData);
    if (!validation.valid) {
      console.log('页面数据验证失败:', validation.errors);
      ctx.status = 400;
      ctx.body = { success: false, message: '页面数据无效', errors: validation.errors };
      return;
    }
    
    // 生成HTML
    console.log('开始生成HTML...');
    const html = htmlGenerator.generateHTML(pageData);
    console.log('HTML生成完成，长度:', html.length);
    
    // 保存预览文件
    console.log('开始保存预览文件...');
    const result = await fileManager.savePreviewHTML(html, filename);
    console.log('保存结果:', result);
    
    if (result.success) {
      ctx.body = result;
    } else {
      ctx.status = 500;
      ctx.body = result;
    }
  } catch (error) {
    console.error('预览生成错误:', error);
    ctx.status = 500;
    ctx.body = { success: false, message: '预览生成失败', error: error.message };
  }
});

// 添加文件管理相关API
router.delete('/api/delete/:filename', async (ctx) => {
  try {
    const { filename } = ctx.params;
    const result = await fileManager.deletePage(filename);
    
    if (result.success) {
      ctx.body = result;
    } else {
      ctx.status = 500;
      ctx.body = result;
    }
  } catch (error) {
    ctx.status = 500;
    ctx.body = { success: false, message: '删除失败', error: error.message };
  }
});

// 获取文件信息
router.get('/api/file-info/:filename', async (ctx) => {
  try {
    const { filename } = ctx.params;
    const result = await fileManager.getFileInfo(filename);
    ctx.body = result;
  } catch (error) {
    ctx.status = 500;
    ctx.body = { success: false, message: '获取文件信息失败', error: error.message };
  }
});

// 清理临时文件
router.post('/api/cleanup', async (ctx) => {
  try {
    const { maxAge } = ctx.request.body;
    const result = await fileManager.cleanupTempFiles(maxAge);
    ctx.body = result;
  } catch (error) {
    ctx.status = 500;
    ctx.body = { success: false, message: '清理失败', error: error.message };
  }
});

// 启动服务器
const PORT = process.env.PORT || 3000;

// 初始化服务器
const startServer = async () => {
  try {
    // 确保必要目录存在
    await fileManager.ensureDirectories();
    
    // 设置路由
    app.use(router.routes()).use(router.allowedMethods());
    
    // 启动服务器
    app.listen(PORT, () => {
      console.log(`服务器运行在 http://localhost:${PORT}`);
      console.log(`页面编辑器: http://localhost:${PORT}`);
    });
  } catch (error) {
    console.error('服务器启动失败:', error);
    process.exit(1);
  }
};

// 启动服务器
startServer();
